package cn.darkhorse.device.service.impl;

import cn.darkhorse.device.pojo.MesOilCategory;
import cn.darkhorse.device.mapper.MesOilCategoryMapper;
import cn.darkhorse.device.service.MesOilCategoryService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.utils.SecurityUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 油耗分类 服务实现类
 * </p>
 *
 * @author yangtianqi
 * @since 2024-11-06
 */
@Service
public class MesOilCategoryServiceImpl extends ServiceImpl<MesOilCategoryMapper, MesOilCategory> implements MesOilCategoryService {

    @Override
    public List<MesOilCategory> list(MesOilCategory mesOilCategory) {
        LambdaQueryWrapper<MesOilCategory> wrapper = new LambdaQueryWrapper<>();
        if (mesOilCategory.getModel()!=null){
            wrapper.like(MesOilCategory::getModel, mesOilCategory.getModel());
        }
        if (mesOilCategory.getCode()!=null){
            wrapper.like(MesOilCategory::getCode, mesOilCategory.getCode());
        }
        if (mesOilCategory.getEnable()!=null){
            wrapper.eq(MesOilCategory::getEnable, mesOilCategory.getEnable());
        }

        return list(wrapper);
    }

    @Override
    public boolean saveMesOilCategory(MesOilCategory mesOilCategory) {
        if (mesOilCategory.getId()==null){

            Long count = lambdaQuery().eq(MesOilCategory::getCode, mesOilCategory.getCode()).count();
            if (count>0){
                throw new RuntimeException("编码已存在");
            }
            Long modelCount = lambdaQuery().eq(MesOilCategory::getModel, mesOilCategory.getModel()).count();
            if (modelCount>0){
                throw new RuntimeException("型号已存在");
            }
            mesOilCategory.setCreateBy(SecurityUtils.getUsername());
            mesOilCategory.setCreateTime(LocalDateTime.now());
        }else {
            Long count = lambdaQuery().eq(MesOilCategory::getCode, mesOilCategory.getCode()).ne(MesOilCategory::getId,mesOilCategory.getId()).count();
            if (count>0){
                throw new RuntimeException("编码已存在");
            }
            Long modelCount = lambdaQuery().eq(MesOilCategory::getModel, mesOilCategory.getModel()).ne(MesOilCategory::getId,mesOilCategory.getId()).count();
            if (modelCount>0){
                throw new RuntimeException("型号已存在");
            }
        }


        return saveOrUpdate(mesOilCategory);
    }

    @Override
    public boolean delete(Long id) {
        return removeById(id);
    }

    @Override
    public MesOilCategory view(Long id) {
        return getById(id);
    }
}
